﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;

using CE.User;
using CE.Global;
using CE.Provider;
using CE.Image;

public partial class Provider_CarInsurance_ProviderPolicyWriting : System.Web.UI.Page
{
    string PageName = "CXCI";
    string SubPageName = "CXCIPLWRT";
    public static Int64 _providerdocumentid = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null || Session[CE.Global.General.ProviderCompanyId] == null)
        {
            Response.Redirect("~/Provider/ProviderSecureLogin.aspx");
        }
        CheckMainPageAccess();
        CheckSubPageAccess();

        if (!IsPostBack)
        {
            ClearProcess();
            if (Request.Params["PWID"] != null)
            {
                Int32 _policydocid;
                if (Int32.TryParse(Request.Params["PWID"].ToString(), out _policydocid))
                {
                    ShowPolicy(_policydocid);
                }
            }
        }
    }

    private void ShowPolicy(Int64 DocumentId)
    {
        ProviderPolicyDocument _policydoc = new ProviderPolicyDocument();
        ProviderPolicyDocumentDB _policydocdb = new ProviderPolicyDocumentDB();

        _policydoc = _policydocdb.GetProviderPolicyDocument(DocumentId);

        if (_policydoc != null)
        {
            lblProviderCarPolicyId.Text = _policydoc.DocumentId.ToString();
            txtPolicyDoc.Text = _policydoc.DocumentName;
            txtPolicyDescription.Text = _policydoc.Description;
            FileInfo _file = new FileInfo(Server.MapPath(_policydoc.UploadPath));
            if (_file.Exists)
            {
                lnkpolicydoc.NavigateUrl = _policydoc.UploadPath.ToString();
                rfvfleUpload.Enabled = false;
                lnkpolicydoc.Text = _file.Name + " (" + (_file.Length / 1024).ToString("#") + " KB)";
            }
            chkStatus.Checked = Convert.ToBoolean(_policydoc.Status);
        }

    }

    public void ClearProcess()
    {
        _providerdocumentid = 0;
        lblProviderCarPolicyId.Text = "0";
        lnkpolicydoc.NavigateUrl = "";
        lnkpolicydoc.Text = "None";
        txtPolicyDoc.Text = "";
        txtPolicyDescription.Text = "";
        lnkpolicydoc.Text = "";
        chkStatus.Checked = true;
        lblMessage.Text = "";

        rfvfleUpload.Enabled = true;

    }

    protected void btnClearForm_Click(object sender, EventArgs e)
    {
        ClearProcess();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string _authcode = CE.Security.MySecurity.Encrypt(txtAuthCode.Text, true);

            bool _fileexist = false;
            bool _fileuploaded = false;
            bool _fileupdate = false;
            int fileSize = 0;

            string strFilename = "";
            string _strDocPath = "";
            string uploadPath = "";
            string providerFolder = "";

            if (CheckAuthCode(_authcode, 100))
            {
                if (fleUpload.PostedFile.FileName != string.Empty || lnkpolicydoc.NavigateUrl != string.Empty)
                {
                    _fileuploaded = true;
                    if (fleUpload.PostedFile.FileName != string.Empty)
                    {
                        _fileupdate = true;
                        HttpPostedFile myFile = fleUpload.PostedFile;
                        fileSize = myFile.ContentLength;
                        FileInfo fInfo = new FileInfo(myFile.FileName);

                        if (fileSize > 0 && (fileSize / 1024) < 4096)
                        {
                            if (CheckExtension(fInfo.Extension) == true)
                            {

                                MyImage myImage = new MyImage();
                                // Allocate a buffer for reading of the file
                                byte[] myData = new byte[fileSize];

                                // Read uploaded file from the Stream
                                myFile.InputStream.Read(myData, 0, fileSize);


                                if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                                    providerFolder = "Liberty/";
                                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EtiqaProviderCompanyId"))
                                    providerFolder = "Etiqa/";
                                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                                    providerFolder = "HSBC/";
                                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("RSAProviderCompanyId"))
                                    providerFolder = "RSA/";

                                strFilename = Path.GetFileName(myFile.FileName);
                                _strDocPath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("UploadDocPath");
                                uploadPath = Server.MapPath(_strDocPath + providerFolder + strFilename);

                                //check if directory exists
                                string directoryToUpload = uploadPath;


                                if (!Directory.Exists(directoryToUpload))
                                {
                                    //creates the folder
                                    string pathtocreate = Server.MapPath(_strDocPath + providerFolder.Remove(providerFolder.Length - 1, 1));
                                    Directory.CreateDirectory(pathtocreate);
                                }
                                _fileexist = File.Exists(uploadPath);
                                if (!_fileexist)
                                {
                                    myImage.WriteToFile(uploadPath, ref myData);
                                }
                                else
                                {
                                    _fileuploaded = false;
                                    lblMessage.Text = "File already exists.";
                                }
                            }
                            else
                            {
                                _fileuploaded = false;
                                lblMessage.Text = "Only PDF Files can be attached.";
                            }
                        }
                        else
                        {
                            _fileuploaded = false;
                            lblMessage.Text = "File size should be under 4 MB.";
                        }
                    }
                }

                if (_fileuploaded)
                {

                    // Write data into a file
                    ProviderPolicyDocument _policydoc = new ProviderPolicyDocument();
                    ProviderPolicyDocumentDB _policydocdb = new ProviderPolicyDocumentDB();
                    int _trantype = 1;
                    _policydoc.DocumentId = Convert.ToInt64(lblProviderCarPolicyId.Text);
                    if (_policydoc.DocumentId > 0)
                    {
                        _trantype = 2;
                        _policydoc = _policydocdb.GetProviderPolicyDocument(_policydoc.DocumentId);
                    }
                    _policydoc.DocumentName = txtPolicyDoc.Text.Trim();
                    _policydoc.Description = txtPolicyDescription.Text.Trim();
                    _policydoc.ForWhat = "CR";
                    if (_fileupdate)
                    {
                        _policydoc.SizeKB = fileSize;
                        _policydoc.UploadPath = _strDocPath + providerFolder + strFilename;
                    }
                    _policydoc.ProviderCompanyId = Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString());
                    _policydoc.RefCEUserId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                    _policydoc.Status = Convert.ToBoolean(chkStatus.Checked.ToString());
                    _policydoc.DocumentId = _policydocdb.Insert(_policydoc);

                    if (_policydoc.DocumentId > 0)
                    {
                        ClearProcess();
                        InsertProviderAuthTransaction(_policydoc.DocumentId, "CICarPolicyWriting", _trantype, 100, _authcode, _policydoc.ProviderCompanyId, _policydoc.RefCEUserId);
                        lblMessage.Text = "Saved successfully!";
                        Response.Redirect("ViewProviderPolicyWriting.aspx");
                    }
                    else
                    {
                        lblMessage.Text = "Saving failed!";
                    }

                }
            }
            else
            {
                lblMessage.Text = "Wrong auth code!";
            }

        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        rfvAuthCode.Validate();
        if (lblProviderCarPolicyId.Text != "0" && txtAuthCode.Text.Trim().Length > 0)
        {
            Int64 _providercompanyid = Convert.ToInt64(Session[General.ProviderCompanyId].ToString());
            string _authcode = CE.Security.MySecurity.Encrypt(txtAuthCode.Text, true);
            Int64 _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
            if (CheckAuthCode(_authcode, 100))
            { 
                ProviderPolicyDocumentDB _policydocdb = new ProviderPolicyDocumentDB();
                ProviderPolicyDocument _policydoc = new ProviderPolicyDocument();

                _policydoc = _policydocdb.GetProviderPolicyDocument(Convert.ToInt64(lblProviderCarPolicyId.Text));
                FileInfo _file = new FileInfo(Server.MapPath(_policydoc.UploadPath));
            
                    if (_policydocdb.Delete(Convert.ToInt64(lblProviderCarPolicyId.Text), _providercompanyid))
                    {
                        if (_file.Exists)
                            _file.Delete();

                        InsertProviderAuthTransaction(Convert.ToInt64(lblProviderCarPolicyId.Text), "CICarPolicy", 3, 100, _authcode, _providercompanyid, _refceuserid);
                        Response.Redirect("ViewProviderPolicyWriting.aspx");
                    }
                    else
                    {
                        lblMessage.Text = "Deleting failed.";
                    }
               
            }
            else
            {
                lblMessage.Text = "Wrong auth code!";
            }
        }

    }

    protected void ibtBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("ViewProviderPolicyWriting.aspx");
    }

    private static bool CheckExtension(string Extension)
    {
        //string[] extList = { ".doc", ".pdf", ".docx", ".txt", ".rtf", ".ppt", ".pptx", ".xls" };
        string[] extList = { ".pdf" };
        bool isInList = false;
        for (int i = 0; i < extList.Length; i++)
        {
            if (Extension == extList[i])
            {
                isInList = true;
                break;
            }
        }
        return isInList;
    }

    protected bool CheckAuthCode(string strAuthCode, int intAuthCodeType)
    {
        bool _retValue = false;
        ProviderAuthCode _authcode = new ProviderAuthCode();
        ProviderAuthCodeDB _authcodedb = new ProviderAuthCodeDB();
        _authcode = _authcodedb.GetProviderAuthCode(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()), intAuthCodeType, strAuthCode);
        if (_authcode != null)
        {
            _retValue = true;
        }

        return _retValue;
    }

    protected Int64 InsertProviderAuthTransaction(Int64 TransactionId, string TransactionCode, int TransactionType,
        int AuthCodeType, string AuthCode, Int64 ProviderCompanyId, Int64 RefCEUserId)
    {
        ProviderAuthTransaction _authtrans = new ProviderAuthTransaction();
        ProviderAuthTransactionDB _authtransdb = new ProviderAuthTransactionDB();

        _authtrans.TransactionId = TransactionId;
        _authtrans.TransactionCode = TransactionCode;
        _authtrans.TransactionType = TransactionType;
        _authtrans.AuthCode = AuthCode;
        _authtrans.AuthCodeType = AuthCodeType;
        _authtrans.ProviderCompanyId = ProviderCompanyId;
        _authtrans.RefCEUserID = RefCEUserId;

        _authtrans.AuthTransId = _authtransdb.Insert(_authtrans);
        return _authtrans.AuthTransId;
    }

    private void CheckMainPageAccess()
    {
        Int64 PageAccess = General.GetProviderMainPageAccess(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()),
                                                        Convert.ToInt64(Session[General.UserId].ToString()), PageName);
        if (PageAccess == 0)
        {
            //Response.Redirect("~/Provider/UserMessage.aspx?errorcode=2000");
            Response.Redirect("~/Provider/UserMessage.aspx?mt=UM&ec=2000");
        }
    }

    private void CheckSubPageAccess()
    {
        Int64 PageAccess = General.GetProviderSubPageAccess(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()),
                                                        Convert.ToInt64(Session[General.UserId].ToString()), SubPageName);
        if (PageAccess == 0)
        {
            //Response.Redirect("~/Provider/UserMessage.aspx?errorcode=2000");
            Response.Redirect("~/Provider/UserMessage.aspx?mt=UM&ec=2000");
        }
        else if (PageAccess == 100)
        {
            ibtSubmit.Enabled = false;
            btnNew.Enabled = false;
            btnDelete.Enabled = false;
        }
        else if (PageAccess == 200)
        {
            ibtSubmit.Enabled = true;
            btnNew.Enabled = true;
            btnDelete.Enabled = false;
        }
        else if (PageAccess == 300)
        {
            ibtSubmit.Enabled = true;
            btnNew.Enabled = true;
            btnDelete.Enabled = true;
        }
    }

}
